//
//  HomeViewController.m
//  Brand
//
//  Created by Faker on 4/8/14.
//  Copyright (c) 2014 Faker. All rights reserved.
//

#import "HomeViewController.h"
#import "IntroViewController.h"
#import "VideoViewController.h"
#import "NewsVC.h"
#import "NewsDetailVC.h"
#import "VideoDetailVC.h"
#import "VideoInfoVC.h"
#import "CarouselObj.h"
#import "VideoObj.h"
#import "Header.h"
#import "config.h"
#import "PhotoViewController.h"


#define IntrolTop       109
#define NewsLeft        113
#define WallpaperLeft   118
#define PersonTop       105
#define MiddleViewLeft  313

@interface HomeViewController ()

@property (weak, nonatomic) IBOutlet UIButton *homeBtn;
@property (weak, nonatomic) IBOutlet UIButton *videoBtn;
@property (weak, nonatomic) IBOutlet UIButton *photoBtn;
@property (weak, nonatomic) IBOutlet UIButton *meBtn;
@property (weak, nonatomic) IBOutlet UIView *navTopContentView;

@property (strong, nonatomic) NSArray* containerArray;

@property (strong, nonatomic) CircleScrollView* myScrollView;
@property (strong, nonatomic) IBOutlet UIView *middleVideoView;
@property (weak, nonatomic) IBOutlet UIButton *rightBtn;
@property (weak, nonatomic) IBOutlet UIImageView *rotation;
@property (weak, nonatomic) IBOutlet UIImageView *outCircleImageView;


@property (strong, nonatomic) NSMutableArray* dataArray;

@end

@implementation HomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.dataArray = [[NSMutableArray alloc]init];
    [[NSBundle mainBundle]loadNibNamed:@"MiddleVideoCell" owner:self options:nil];
    self.middleVideoView.left = 7;
    if(!isiPhone5)
    {
        self.videoBtn.top -= 15;
        self.photoBtn.top += 15;
    }
    self.middleVideoView.top = isiPhone5 ? 183 : 142;
    self.middleVideoView.left = -306;
    CGRect frame = CGRectMake(1, 1, 263, 158);
    self.myScrollView = [[CircleScrollView alloc]initWithFrame:frame andPageXibName:@"CircleScrollCell"];
    self.myScrollView.isCircle = YES;
    self.myScrollView.layer.cornerRadius = 5;
    self.myScrollView.clipsToBounds = YES;
    self.myScrollView.delegate = self;
    
    [self.middleVideoView addSubview:self.myScrollView];
    [self.view addSubview:self.middleVideoView];
    
    
    
   
    if(!isiPhone5)
    {
        self.rotation.top -= 20;
        self.outCircleImageView.top -= 20;
    }

   if(!isiOS6)
   {
    [[MyMotionManager sharedInstance] moveView:self.rotation andOutView:self.outCircleImageView andUpdateInterVal:0.08 andScrollXYZ:@"z" andIsRight:YES];
}
    [self prepareGetData];

}


#pragma mark - 网络请求
-(void)prepareGetData
{
    [kApp displayWaitViewWithAllMaskView:NO];
    NSString* url = [NSString stringWithFormat:@"%@scrollView&type=0",API_BASE];
    [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        if(isSuccess)
        {
            [self getDataSuccessWithData:responseObj];
        }
        else{
            [self getDataError];
        }
    }];
}

-(void)getDataSuccessWithData:(id)responseObj
{
    [kApp hideWaitView];
    
    NSArray* tempArray = (NSArray*)responseObj;
    NSMutableArray* mArray = [NSMutableArray array];
    for (NSDictionary* dic in tempArray) {
        
        CarouselObj* carouseObj = [[CarouselObj alloc]init];
        carouseObj.title = [dic objectForKey:@"title"];
        carouseObj.type = [dic objectForKey:@"type"];
        carouseObj.pic = [dic objectForKey:@"pic"];
        carouseObj.idOrUrl = [dic objectForKey:@"id_url"];
        [mArray addObject:carouseObj];
    }
    self.dataArray = mArray;
    [UserDataBasic saveThisObjectArray:self.dataArray forArrayKey:LocalCarouseData]; //存本地
    [self handleDetail];
    
}

-(void)getDataError
{
    [kApp hideWaitView];
    [PopTips tips:self.view Msg:NotifyNoNet];
    
    if([self.dataArray count] != 0) //内存中有值
    {
        return;
    }
    else
    {
        self.dataArray = [UserDataBasic readObjectArrayForKey:LocalCarouseData];
        if([self.dataArray count] !=0) //取到了值才会去刷新
        {
            [self handleDetail];
        }
    }
}

-(void)handleDetail
{
    [self.myScrollView drawContainerWithTotalNums:self.dataArray.count andOrientation:CircleOrientationLandscape];
}



-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if([[kHandle sharedInstance] isShowTrueView])
    {
        self.rightBtn.hidden = NO;
    } else {
        self.rightBtn.hidden = YES;
    }
    self.dataArray = [UserDataBasic readObjectArrayForKey:LocalCarouseData];
    if(!IsNull(self.dataArray)&&self.dataArray.count>0)
    {
    [self.myScrollView drawContainerWithTotalNums:self.dataArray.count andOrientation:CircleOrientationLandscape];
    }

    
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];

    if(!isiOS6){[self startAnimation];}
}


-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if(isiOS6)
    {
        [self startAnimation];
    }
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    
    if(!isiOS6){[self initPosition];}
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if(isiOS6) {[self initPosition];}
    
}



#pragma mark - Animation

-(void)startAnimation
{
    CGFloat delay = 0;
   
    [UIView animateWithDuration:0.5f
                          delay:delay
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                                    self.view.userInteractionEnabled = NO;
                                    self.homeBtn.top += IntrolTop;
                                    self.videoBtn.left -= NewsLeft;
                                    self.photoBtn.left += WallpaperLeft;
                                    self.meBtn.top -= PersonTop;
                                    self.middleVideoView.left += MiddleViewLeft;
    } completion:^(BOOL finished) {
        self.view.userInteractionEnabled = YES;
    }];

}

-(void)initPosition
{
    self.homeBtn.top -= IntrolTop;
    self.videoBtn.left += NewsLeft;
    self.photoBtn.left -= WallpaperLeft;
    self.meBtn.top += PersonTop;
    self.middleVideoView.left -= MiddleViewLeft;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

#pragma mark - CircleScrollViewDelegate

-(void)circleScrollView:(UIScrollView *)scrollView refreshThePageWithIndexArray:(NSArray *)indexArray
{
    for (int i = 0; i<indexArray.count; i++) {
        UIView* pageView = [scrollView.subviews objectAtIndex:i];
        
        int index = (int)[[indexArray objectAtIndex:i] integerValue];
        CarouselObj* carouseObj = [self.dataArray objectAtIndex:index];
        
        UILabel* indexLabel = (UILabel*)[pageView viewWithTag:200];
        UIButton* btn = (UIButton*)[pageView viewWithTag:201];
        UIImageView* imageView = (UIImageView*)[pageView viewWithTag:302];
        
        btn.titleLabel.text = [NSString stringWithFormat:@"%d",index];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        indexLabel.text = carouseObj.title;
        [[AFGetData sharedInstance] initSDWebImage:carouseObj.pic andTrueImageView:imageView andPlaceholderImage:nil];
    }
}

-(void)btnClick:(id)sender
{
   
    UIButton* btn = (UIButton*)sender;
    int index = [btn.titleLabel.text integerValue];
    
    CarouselObj* carouselObj = [self.dataArray objectAtIndex:index];
   
    NewsDetailVC* newsVC = [[NewsDetailVC alloc]initWithNibName:@"NewsDetailVC" bundle:nil];
    VideoDetailVC* detailVC = [[VideoDetailVC alloc]initWithNibName:@"VideoDetailVC" bundle:nil];
    
    if([carouselObj.type isEqualToString:@"1"])
    {
       
        VideoObj* videoObj = [[VideoObj alloc]init];
        videoObj.contentName = carouselObj.title;
        videoObj.episodeId = carouselObj.idOrUrl;
        detailVC.videoObj = videoObj;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    else
    {
        //newsVC.url = carouselObj.idOrUrl;
        newsVC.title = carouselObj.title;
        NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:carouselObj.idOrUrl,@"url", nil];
        NSArray* dataArrray = [NSArray arrayWithObjects:dic, nil];
        newsVC.dataArray = dataArrray;
        [self.navigationController pushViewController:newsVC animated:YES];
        [Common getWYByPostWithType:@"3" andItemId:@"0"];
    }
    
}


#pragma mark - Go To View Controllers
- (IBAction)goToHomeVC:(id)sender {
    IntroViewController* introVC = [[IntroViewController alloc]initWithNibName:@"IntroViewController" bundle:nil];
    [self.navigationController pushViewController:introVC animated:YES];
}
- (IBAction)goToVideoVC:(id)sender {
    NewsVC* newsVC =[[NewsVC alloc]initWithNibName:@"NewsVC" bundle:nil];
    //VideoInfoVC* infoVC = [[VideoInfoVC alloc]initWithNibName:@"VideoInfoVC" bundle:nil];
    [self.navigationController pushViewController:newsVC animated:YES];
}

- (IBAction)goToVideo:(id)sender {
    VideoViewController* videoVC = [[VideoViewController alloc]initWithNibName:@"VideoViewController" bundle:nil];
    [self.navigationController pushViewController:videoVC animated:YES];
}

- (IBAction)goToPhotoVC:(UIButton *)sender {
    UIViewController *photoVC = [PhotoViewController new];
    [self.navigationController pushViewController:photoVC  animated:YES];
}
- (IBAction)goToMeVC:(UIButton *)sender {
    kApp.meHomeVC = [[MeHomeViewController alloc] initWithNibName:@"MeHomeViewController" bundle:nil];
    [self.navigationController pushViewController:kApp.meHomeVC animated:YES];
}




#pragma mark - Autorotate

/*
-(BOOL) shouldAutorotate {
	return NO;
}

-(NSUInteger) supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
*/

#pragma mark - StatusBarHidder

-(BOOL)prefersStatusBarHidden
{
    return YES;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation
{
    return UIStatusBarAnimationNone;
}


@end
